#
#   __init__.py.py
#   journalismManger
#
#   Created by luoxh on 2019-07-22-11:00.
#   Copyright © 2019 luoxh. All rights reserved.
#

from flask import (redirect, render_template, request, url_for, )

from src.extension.auth import _session_id, current_user, del_session_msg, login_required, not_login, set_session_msg
from src.extension.blueprints import Blueprint
from src.extension.utils import HTMLEntitiesToUnicode, is_get
from src.model.home.news import News, NewsType
from src.validator.admin import valid_admin_login
from src.viewmodel.admin import AdminVM

admin_bp = Blueprint('admin', __name__, url_prefix='/admin')


@admin_bp.route('/login', methods=['GET', 'POST'])
@not_login
def login():
    if is_get(request): return render_template('admin/login.html')
    set_session_msg(valid_admin_login(request).username)
    return redirect(url_for('.index'))


@admin_bp.route('/logout')
def logout():
    del_session_msg(_session_id())
    return redirect(url_for('.login'))


@admin_bp.route(('', '/', '/index'))
@login_required
def index(): return render_template('admin/index.html')


@admin_bp.route('/profile')
@login_required
def profile(): return render_template('admin/profile.html', **AdminVM(current_user()))


@admin_bp.route('/news_form', methods=['GET', 'POST'])
@login_required
def news_form():
    if is_get(request): return render_template('admin/news_form.html')
    title = request.data['title']
    author = request.data['author']
    content = request.data['content']
    news_type = request.data['news_type']
    media_type = request.data['media_type']
    News(title=title, author=author, content=HTMLEntitiesToUnicode(content),
         news_type=NewsType.objects.get(name=news_type), media_type=media_type).save()
    return redirect(url_for("admin.news_form"))


@admin_bp.route('/upload', methods=['POST'])
@login_required
def upload():
    pass
